package com.genghis.ptas.question.service.impl;

import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.question.dao.AnswerDao;
import com.genghis.ptas.question.entity.Answer;
import com.genghis.ptas.question.service.AnswerService;
import com.genghis.ptas.security.entity.User;
import com.genghis.ptas.security.service.UserService;
import com.genghis.ptas.system.service.DictService;
import com.genghis.ptas.util.DateUtil;
import com.genghis.ptas.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: gaoyang
 * To change this template use File | Settings | File Templates.
 */
@Service("answerService")
public class AnswerServiceImpl implements AnswerService {
    @Autowired
    private AnswerDao answerDao;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    @Override
    public void addAnswer(Answer answer) {
        String loginName = LoginUserUtil.findLoginUserName();
        User user = userService.findUserByLoginName(loginName);
        answer.setUserId(user.getId());
        answer.setIsAdopted(0);
        answer.setAnswerDate(DateUtil.getSystemDate(DictConstant.DATE_FORMAT));
        answerDao.addAnswer(answer);
    }

    @Override
    public void editAnswer(Answer answer) {
        Answer oldAnswer=findAnswerById(answer.getId());
        oldAnswer.setAnswerContent(answer.getAnswerContent());
        answerDao.editAnswer(oldAnswer);
    }

    @Override
    public void delAnswerByIds(String ids) {
        answerDao.delAnswerByIds(ids);
    }

    @Override
    public void delAnswerByQuestionId(String ids) {
        answerDao.delAnswerByQuestionId(ids);
    }

    @Override
    public Answer findAnswerById(int id) {
        return answerDao.findAnswerById(id);
    }

    @Override
    public List<Answer> findAllAnswerByQuestionId(Integer questionId) {
        List<Answer> answerList = answerDao.findAllAnswerByQuestionId(questionId);
        for(Answer answer : answerList){
            answer.setShowIsAdopted(dictService.changeDictCodeToValue(answer.getIsAdopted() , DictConstant.IS_ADOPTED));
        }
        return answerList;
    }

    @Override
    public void adoptAnswer(Answer answer) {
        Answer answer1 = answerDao.findAnswerById(answer.getId());
        answer1.setIsAdopted(DictConstant.IS_ADOPTED_1);
        answerDao.editAnswer(answer1);
    }

    @Override
    public List<Answer> findNewestAnswerByQuestionId(int id) {
        return answerDao.findNewestAnswerByQuestionId(id);
    }
}
